package com.cmwa.solution.base.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cmwa.ec.base.util.SpringUtil;

@Controller
@RequestMapping("/upload")
public class UploadController {
	private static final Log log = LogFactory.getLog(UploadController.class);
	

	/**
	 * 1.信批需求，富文本编辑器图片需要生成word
	 * 2.按原来方式如果上传至KM应用目录下，生成word时，无法通过网络读取文件写入word
	 * 3.信批的上传目标地址改为cbp公用的的应用服务器文件目录
	 * 4.由于不在应用容器目录下，需要通过流读取后写回Response
	 * @param request
	 * @param response
	 * @param url
	 * @throws IOException
	 */
	@RequestMapping("downloadForRichTextEditor")
	public void downloadForRichTextEditor(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "url", defaultValue="")String url) throws IOException {
		if (StringUtils.isEmpty(url)) {
			log.error("下载URL为空");
			return;
		}
		
		String tmpFileBasePath = SpringUtil.getProperty("sys.tmpFileBasePath");
		
		log.info("下载文件:" + url);
		
		if (StringUtils.contains(url, "./") || StringUtils.contains(url, "../")) {
			log.error("下载URL异常：" + url);
			return;
		}
		
		if (!StringUtils.startsWith(url, tmpFileBasePath)) {
			log.error("下载URL异常：" + url);
			return;
		}


		try {
			String fileName = StringUtils.substring(url, StringUtils.lastIndexOf(url, "/") + 1, url.length());
			String type = "";
			String openType = "inline";
			String fileNameExt = "";
			fileNameExt = fileName.substring(fileName.lastIndexOf("."), fileName.length());
			if (fileNameExt.toLowerCase().equals(".pdf")) {
				type = "application/pdf";
			} else if (fileNameExt.toLowerCase().equals(".doc")) {
				type = "application/x-word";
			} else if (fileNameExt.toLowerCase().equals(".docx")) {
				type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
			} else if (fileNameExt.toLowerCase().equals(".xls")) {
				type = "application/vnd.ms-excel";
			} else if (fileNameExt.toLowerCase().equals(".xlsx")) {
				type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
			} else if (fileNameExt.toLowerCase().equals(".bmp")) {
				type = "image/bmp";
			} else if (fileNameExt.toLowerCase().equals(".gif")) {
				type = "image/gif";
			} else if (fileNameExt.toLowerCase().equals(".jpe") || fileNameExt.toLowerCase().equals(".jpeg") || fileNameExt.toLowerCase().equals(".jpg")) {
				type = "image/jpeg";
			} else if (fileNameExt.toLowerCase().equals(".txt")) {
				type = "text/plain";
			} else {
				type = "application/x-msdownload";
				openType = "attachment";
			}
		
			response.reset();
			response.setHeader("Content-Type", type);
			response.setHeader("Content-Disposition", openType + ";filename=" + URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"));
			OutputStream outputStream = null;
			FileInputStream fis = null;
			try {
				File file = new File(url);
				if (!file.exists()) {
					log.error("文件不存在: " + url);
					return;
				}
				
				fis = new FileInputStream(file);
				byte[] buffer = new byte[1024];
				int byteread = 0;

				outputStream = response.getOutputStream();
				while ((byteread = fis.read(buffer)) != -1) {
					outputStream.write(buffer, 0, byteread);
				}

			} catch (Exception ex) {
				ex.printStackTrace();
				log.error("下载异常：", ex);
			} finally {
				try {
					if (outputStream != null) {
						outputStream.close();
					}
					if (fis != null) {
						fis.close();
					}
				} catch (Exception ex2) {
					log.error("关闭流异常", ex2);
				}
			}
		} catch (Exception e) {
			log.error("下载异常：", e);
		}
	}
}
